import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/calendar.dart';
import 'package:geomancy/models/daily_horsecope_model.dart';
import 'package:geomancy/models/huang_li_day_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_shadow_text.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/date_picker/index.dart';
import 'package:geomancy/widgets/stroke_text.dart';
import 'package:go_router/go_router.dart';
import 'package:lunar/lunar.dart';
import 'package:provider/provider.dart';
import 'package:table_calendar/table_calendar.dart';

class CalendarAlmanacPage extends StatefulWidget {
  const CalendarAlmanacPage({super.key});

  @override
  State<CalendarAlmanacPage> createState() => _CalendarAlmanacPageState();
}

class _CalendarAlmanacPageState extends State<CalendarAlmanacPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  double rowHeight = 120.w;
  // 添加 focusedDay 状态变量
  late DateTime _focusedDay;
  // 万年历显示的年月
  late String currentYYMM;
  // 万年历显示的月日
  late String currentMMDD;
  //当日黄历
  HuangLiDayItemModel? dayHuangLi;
  //十二时辰
  late Map<String, String> ganZhiResult;

  @override
  void initState() {
    super.initState();
    _focusedDay = DateTime.now();
    currentYYMM = _getYearAndMonth(_focusedDay);
    currentMMDD = _getMonthAndDay(_focusedDay);
    final int weeksCount = _getWeeksCount(_focusedDay);
    rowHeight = weeksCount == 5 ? 120.w : 100.w;
    ganZhiResult = Utils.getLunarTime(DateTime.now());
    getHuangLi(_focusedDay);
  }

  ///日期转化成农历
  String transformLunarChineseDay(DateTime date) {
    Lunar lunar = Lunar.fromDate(date);
    String lunarDay = '${lunar.getYearInChinese()}${lunar.getMonthInChinese()}${lunar.getDayInChinese()}';
    return lunarDay;
  }

  ///当日黄历
  Future getHuangLi(DateTime date) async {
    try {
      final data = await CalendarAPI.getCurrentDay(context, date);
      setState(() {
        dayHuangLi = data;
      });
    } catch(e) {
      //..
    }
  }

  //获取年月
  String _getYearAndMonth(DateTime focusedDay) {
    final year = _focusedDay.year;
    final month = _focusedDay.month;

    return '$year年$month月';
  }
  //获取月日
  String _getMonthAndDay(DateTime focusedDay) {
    final month = _focusedDay.month;
    final day = _focusedDay.day;

    return '$month月$day日';
  }

  // 添加一个方法来计算行数
  int _getWeeksCount(DateTime focusedDay) {
    // 获取当月第一天
    final firstDayOfMonth = DateTime(focusedDay.year, focusedDay.month, 1);
    // 获取当月最后一天
    final lastDayOfMonth = DateTime(focusedDay.year, focusedDay.month + 1, 0);
    // 计算第一天是星期几（1是周一，7是周日）
    final firstWeekday = firstDayOfMonth.weekday;
    // 计算需要显示的上个月的天数
    final daysFromPreviousMonth = firstWeekday == 7 ? 0 : firstWeekday;
    // 当月的天数
    final daysInMonth = lastDayOfMonth.day;
    // 总共需要显示的天数
    final totalDays = daysFromPreviousMonth + daysInMonth;
    // 返回需要的周数
    return ((totalDays + 6) / 7).floor();
  }

  ///container样式
  BoxDecoration containerStyle() {
    return BoxDecoration(
      color: ColorStyle.themeLightColor,
      border: Border.all(width: 5.w, color: ColorStyle.borderColor),
      borderRadius: BorderRadius.all(Radius.circular(60.w))
    );
  }
  ///运势item
  Widget rowItem({required String txt, required String url, int num = 0}) {
    return Row(
      children: [
        Expanded(child: StrokeText(txt: txt, fontSize: 24.sp, letterSpacing: 1.5)),
        Wrap(
          spacing: 10.w,
          children: List.filled(5, 0).asMap().keys.map((index) {
            return SizedBox(
              width: 27.w,
              height: 22.w,
              child: Image.asset(index < num ? '${url}_active.png' : '$url.png', height: 22.w),
            );
          }).toList(),
        )
      ],
    );
  }

  // 一个简单的节日判断方法（示例）
  String? _getHoliday(DateTime date) {
    Lunar lunar = Lunar.fromDate(date);
    // 获取农历节日
    String? festivals = lunar.getFestivals().join(',');
    // 获取公历节日
    String? otherFestivals = lunar.getOtherFestivals().join(',');
    // 获取节气
    String? jieQi = lunar.getJieQi();
    
    // 按优先级返回节日信息
    if (festivals.isNotEmpty) {
      return festivals;
    } else if (jieQi.isNotEmpty) {
      return jieQi;
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final user = context.watch<UserProvider>().getUserInfo;
    String? zodiac;
    int? zodiacIndex;
    if (user != null && user.birthday != null) {
      zodiacIndex = Utils.getZodiacIndex(user.birthday!.split(' ')[0]);
      zodiac = Utils.getZodiacTxtBybIndex(zodiacIndex);
    }
    return ListView(
      padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, 40.w),
      children: [
        const CommonTitleWidget(txt: '万年历'),
        ///万年历
        Container(
          height: 820.w,
          margin: EdgeInsets.symmetric(vertical: 20.w),
          padding: EdgeInsets.symmetric(vertical: 20.w),
          decoration: containerStyle(),
          child: Column(
            children: [
              GestureDetector(
                onTap: () {
                  DatePickerUtil.show(context, getValue: (String value) {
                    final selectedDay = DateTime.parse(value);
                    setState(() {
                      _focusedDay = selectedDay;
                      currentMMDD = _getMonthAndDay(selectedDay);
                      currentYYMM = _getYearAndMonth(selectedDay);
                    });
                    getHuangLi(selectedDay);
                  });
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CommonShadowTextWidget(txt: currentYYMM),
                    Container(
                      margin: EdgeInsets.only(left: 15.w, top: 10.w),
                      child: Image.asset('assets/icons/icon_arrow_down.png', width: 18.w),
                    )
                  ],
                ),
              ),
              TableCalendar(
                locale: 'zh_CN',
                availableGestures: AvailableGestures.horizontalSwipe,
                firstDay: DateTime.utc(2000, 1, 1),
                lastDay: DateTime.utc(2100, 12, 31),
                focusedDay: _focusedDay,
                calendarFormat: CalendarFormat.month,
                headerVisible: false,
                daysOfWeekHeight: 80.w,
                rowHeight: rowHeight,
                daysOfWeekStyle: DaysOfWeekStyle(
                  dowTextFormatter: (DateTime date, dynamic locale) {
                    // 自定义星期显示格式
                    final weekdays = ['日', '一', '二', '三', '四', '五', '六'];
                    return weekdays[date.weekday % 7];
                  },
                  weekendStyle: TextStyle(color: ColorStyle.red, fontSize: 36.sp, fontWeight: FontWeight.bold), // 周末样式
                  weekdayStyle: TextStyle(color: ColorStyle.textColor, fontSize: 36.sp), // 工作日样式
                ),
                calendarBuilders: CalendarBuilders(
                  // 当前月份之外的日期样式
                  outsideBuilder: (context, date, focusedDay) {
                    Lunar lunar = Lunar.fromDate(date);
                    String lunarDay = lunar.getDayInChinese();
                    String? holiday = _getHoliday(date);
                    return SizedBox(
                      width: 90.w,
                      height: 120.w,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '${date.day}',
                            style: TextStyle(
                              fontSize: 36.sp,
                              color: Colors.grey.withOpacity(0.5), // 使用灰色半透明
                            ),
                          ),
                          if (holiday == null)
                            Text(
                              lunarDay,
                              style: TextStyle(
                                fontSize: 18.sp,
                                color: Colors.grey.withOpacity(0.5), // 使用灰色半透明
                              ),
                            )
                          else
                            Text(
                              holiday,
                              style: TextStyle(
                                fontSize: 18.sp,
                                color: ColorStyle.red.withOpacity(0.5), // 节日颜色半透明
                              ),
                            ),
                        ],
                      ),
                    );
                  },
                  // 保持其他已有的 builder
                  todayBuilder: (context, date, focusedDay) {
                    // 获取农历日期
                    Lunar lunar = Lunar.fromDate(date);
                    String lunarDay = lunar.getDayInChinese(); // 获取农历日期的中文表示
                    // 检查是否为节日
                    String? holiday = _getHoliday(date);
                    return Container(
                      width: 90.w,
                      height: 120.w,
                      decoration: BoxDecoration(
                        color: date == focusedDay ? ColorStyle.themeColor : null,
                        border: Border.all(width: 1.w, color: ColorStyle.themeColor),
                        borderRadius: BorderRadius.all(Radius.circular(20.w))
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '${date.day}',  // 公历日期
                            style: TextStyle(fontSize: 36.sp, color: Colors.black),
                          ),
                          if (holiday == null)
                            Text(
                              lunarDay,  // 农历日期（如：初一、初二等）
                              style: TextStyle(fontSize: 18.sp, color: Colors.black),
                            )
                          else
                            Text(
                              holiday,
                              style: TextStyle(fontSize: 18.sp, color: const Color.fromRGBO(198, 0, 0, 1)),
                            ),
                        ],
                      ),
                    );
                  },
                  defaultBuilder: (context, date, focusedDay) {
                    // 获取农历日期
                    Lunar lunar = Lunar.fromDate(date);
                    String lunarDay = lunar.getDayInChinese(); // 获取农历日期的中文表示
                    // 检查是否为节日
                    String? holiday = _getHoliday(date);
                    return Container(
                      width: 90.w,
                      height: 120.w,
                      decoration: BoxDecoration(
                          color: date == focusedDay ? ColorStyle.themeColor : null,
                          borderRadius: BorderRadius.all(Radius.circular(20.w))
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '${date.day}',  // 公历日期
                            style: TextStyle(fontSize: 36.sp, color: Colors.black),
                          ),
                          if (holiday == null)
                            Text(
                              lunarDay,  // 农历日期（如：初一、初二等）
                              style: TextStyle(fontSize: 18.sp, color: Colors.black),
                            )
                          else
                            Text(
                              holiday,
                              style: TextStyle(fontSize: 18.sp, color: const Color.fromRGBO(198, 0, 0, 1)),
                            ),
                        ],
                      ),
                    );
                  },
                ),
                onDaySelected: (DateTime selectedDay, DateTime focusedDay) {
                  setState(() {
                    _focusedDay = selectedDay;
                    currentMMDD = _getMonthAndDay(selectedDay);
                  });
                  getHuangLi(selectedDay);
                },
                onPageChanged: (focusedDay) {
                  setState(() {
                    _focusedDay = focusedDay;
                    final int weeksCount = _getWeeksCount(focusedDay);
                    rowHeight = weeksCount == 5 ? 120.w : 100.w;
                    currentYYMM = _getYearAndMonth(focusedDay);
                    currentMMDD = _getMonthAndDay(focusedDay);
                  });
                  getHuangLi(focusedDay);
                },
              )
            ],
          )
        ),
        Container(
          decoration: containerStyle(),
          padding: EdgeInsets.fromLTRB(40.w, 20.w, 40.w, 47.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(child: CommonShadowTextWidget(txt: currentMMDD)),
              Container(
                height: 60.w,
                margin: EdgeInsets.only(top: 30.w),
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                ),
                child: CommonText(txt: '农历  ${transformLunarChineseDay(_focusedDay)}(阴历)'),
              ),
              Container(
                height: 60.w,
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                ),
                child: CommonText(txt: '${ganZhiResult['ganZhiYear']}年 ${ganZhiResult['ganZhiMonth']}月 ${ganZhiResult['ganZhiDay']}日 ${ganZhiResult['ganZhiTime']}时 ${zodiac == null ? '' : '[属$zodiac]'}'),
              ),
              ///宜、忌
              Container(
                padding: EdgeInsets.symmetric(vertical: 26.w),
                decoration: BoxDecoration(
                    border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                ),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          margin: EdgeInsets.only(right: 32.w),
                          child: Image.asset('assets/icons/icon_yi.png', height: 40.w),
                        ),
                        Expanded(child: CommonText(txt: dayHuangLi?.y != null ? dayHuangLi!.y!.join(' ') : ''))
                      ],
                    ),
                    SizedBox(height: 12.w),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          margin: EdgeInsets.only(right: 32.w),
                          child: Image.asset('assets/icons/icon_ji.png', height: 40.w),
                        ),
                        Expanded(child: CommonText(txt: dayHuangLi?.j != null ? dayHuangLi!.j!.join(' ') : ''))
                      ],
                    )
                  ],
                ),
              ),
              ///吉神宜趋、凶神宜忌
              Container(
                padding: EdgeInsets.symmetric(vertical: 26.w),
                decoration: BoxDecoration(
                    border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                ),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: 130.w,
                          margin: EdgeInsets.only(right: 25.w),
                          child: const CommonText(txt: '吉神宜趋', weight: FontWeight.bold),
                        ),
                        Expanded(child: CommonText(txt: dayHuangLi?.yq??'-'))
                      ],
                    ),
                    SizedBox(height: 12.w),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: 130.w,
                          margin: EdgeInsets.only(right: 25.w),
                          child: const CommonText(txt: '凶神宜忌', weight: FontWeight.bold),
                        ),
                        Expanded(child: CommonText(txt: dayHuangLi?.yj??'-'))
                      ],
                    )
                  ],
                ),
              ),
              ///冲煞
              Container(
                padding: EdgeInsets.symmetric(vertical: 26.w),
                decoration: BoxDecoration(
                    border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: 130.w,
                      margin: EdgeInsets.only(right: 25.w),
                      padding: EdgeInsets.only(right: 7.w),
                      child: const Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          CommonText(txt: '冲', weight: FontWeight.bold),
                          CommonText(txt: '煞', weight: FontWeight.bold),
                        ],
                      )
                    ),
                    Expanded(child: CommonText(txt: '${dayHuangLi?.c} ${dayHuangLi?.s}'))
                  ],
                ),
              ),
              ///吉神宜趋、凶神宜忌
              Container(
                padding: EdgeInsets.symmetric(vertical: 26.w),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: 130.w,
                          margin: EdgeInsets.only(right: 25.w),
                          child: const CommonText(txt: '胎神占方', weight: FontWeight.bold),
                        ),
                        Expanded(child: CommonText(txt: dayHuangLi?.ts??'-'))
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                margin: EdgeInsets.only(top: 20.w),
                child: Wrap(
                  alignment: WrapAlignment.center,
                  spacing: 6.w,
                  children: [
                    CommonBtnWidget(txt: '择吉日', fontSize: 30.sp, size: Size(252.w, 80.w), onTap: (){
                      context.push('/good_day');
                    }),
                    CommonBtnWidget(txt: '择吉时', fontSize: 30.sp, size: Size(252.w, 80.w), onTap: (){
                      context.push('/good_occasion', extra: {
                        "date": _focusedDay
                      });
                    }),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                alignment: Alignment.center,
                margin: EdgeInsets.only(top: 20.w),
                child:  CommonBtnWidget(txt: '黄历名词解释大全', fontSize: 30.sp, size: Size(510.w, 80.w), onTap: (){
                  context.push('/nouns_list');
                }),
              ),
            ],
          ),
        )
      ],
    );
  }
}
